package com.example.imchat.controller.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.example.imchat.R;
import com.example.imchat.model.bean.PickContactInfo;

import java.util.ArrayList;
import java.util.List;

/*
* 创建群聊 选择群成员的适配器
* */
public class PcikContactAdapter extends BaseAdapter {
    private  Context mContext;
    private List<PickContactInfo> mPicks  = new ArrayList<>();
    private List<String> mExistMembers = new ArrayList<>();
    public PcikContactAdapter(Context context, List<PickContactInfo> picks,List<String> existMembers) {
        mContext = context;
        if (null != picks && picks.size() >= 0) {
            mPicks.clear();
            mPicks.addAll(picks);
        }

        //已经存在的成员集合
        mExistMembers.clear();
        if (existMembers == null){
            return;
        }else {

            mExistMembers.addAll(existMembers);
        }
    }
    @Override
    public int getCount() {
        return mPicks == null? 0 :mPicks.size();
    }

    @Override
    public Object getItem(int position) {
        return mPicks.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //创建获取viewholder
        ViewHolder holder = null;
        if (null== convertView){
            holder = new ViewHolder();

            convertView = View.inflate(mContext, R.layout.item_pick,null);
            holder.cb_pick = convertView.findViewById(R.id.cb_pick);
            holder.tv_pick_name = convertView.findViewById(R.id.tv_pick_name);

            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        //获取item数据
        PickContactInfo pickContactInfo = mPicks.get(position);
        //显示数据
        holder.tv_pick_name.setText(pickContactInfo.getUser().getName());
        holder.cb_pick.setChecked(pickContactInfo.isChecked());
        //判断
        if (mExistMembers.contains(pickContactInfo.getUser().getHxid())){
            holder.cb_pick.setChecked(true);
            pickContactInfo.setChecked(true);
        }
        return convertView;
    }
        //获取选择联系人
    public List<String> getPickContacts() {
        List<String> picks = new ArrayList<>();
        for (PickContactInfo pick : mPicks){
            if (pick.isChecked()){
                picks.add(pick.getUser().getName());
            }
        }
        return picks;
    }


    private class  ViewHolder{
        private CheckBox cb_pick;
        private TextView tv_pick_name;

    }
}
